#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
账户管理handle模块
'''

from lib.myweb import WebApplication
from lib.validate import Check
from lib.validate import Filter
from lib.sqldata import ModelSession

from common import auth
from common.myconfig import CONF
from common.myvalidate import ValidatorCommon
from common.mydata import ModelUser


class FilterPassport(Filter):
    '账户模块专用过滤器'
    @staticmethod
    def passwd_hash(username, passwd):
        '对密码进行hash加密'
        import hashlib

        content = username + passwd + CONF['passwd_key']

        sign = hashlib.sha1(content).hexdigest()
        return sign


class ValidatorPassport(ValidatorCommon):
    '账户模块专用校验器'
    @staticmethod
    @Check.is_empty
    def check_path(target_str):
        '检查路径'
        return True

    @staticmethod
    @Check.is_len_range(6, 20)
    @Check.is_alnum(True)
    def check_username(target_str):
        '检查用户名'
        return True

    @staticmethod
    @Check.is_len_range(6, 20)
    @Check.is_re_match('^[x00-x7f]*$')
    def check_passwd(target_str):
        '检查密码'
        return True

    @staticmethod
    @Check.is_len_range(4, 20)
    @Check.is_re_match(u'^[a-zA-Z\u4E00-\u9FA5 ]*$')
    def check_realname(target_str):
        '检查真实姓名'
        return True

    @staticmethod
    @Check.is_date('%Y-%m-%d')
    def check_birthday(target_str):
        '检查生日，包含日期逻辑'
        return True

    @staticmethod
    @Check.is_len_range(11)
    @Check.is_digit(True)
    def check_mobile(target_str):
        '检查手机号'
        return True

    @staticmethod
    @Check.is_len_range(6)
    @Check.is_digit(True)
    def check_postcode(target_str):
        '检查邮编'
        return True

    @staticmethod
    @Check.is_len_range(20, 100)
    def check_address(target_str):
        '检查地址'
        return True


class HandlePassport(WebApplication):
    '账户管理handle'
    _HANDLE_NAME = 'passport'  # handle名称，用于模板前缀
    _PATH_PREFIX = '/passport'  # 一级路径名称，用于解析path

    @auth.session(auth.SESSION_LEVEL['visitor'])
    def action_login(self):
        '登录表单页面'
        query = self._request.query
        path_info, error_type = ValidatorPassport.check_from_dict(
                query, ['path', ])
        if error_type:
            path = ''
        else:
            path = path_info['path']
        self._render.view['path'] = path

    @auth.method('post')
    @auth.session(auth.SESSION_LEVEL['visitor'])
    def action_loginproc(self):
        '登录处理页面'
        import urllib
        import uuid

        expir_sec = CONF['expir_sec']
        sn_name = CONF['sn_name']

        form = self._request.form
        check_list = [
                'username',
                'passwd',
                'path',
                ]
        user_info, error_type = ValidatorPassport.check_from_dict(
                form, check_list)
        if error_type:
            return self.error_type(error_type)
        path = urllib.unquote(user_info['path'])

        # 从数据库检查用户登录信息
        mod_usr = ModelUser()
        passwd = FilterPassport.passwd_hash(
                user_info['username'], user_info['passwd'])
        user_info = mod_usr.get_user_by_passwd(user_info['username'], passwd)
        self._render.view['user_info'] = user_info
        if not user_info:
            return self.error_type('not_exist')

        # 创建session
        data = {}
        data['user_id'] = user_info['id']
        data['token'] = uuid.uuid4().hex
        mod_ss = ModelSession()
        sn_num = mod_ss.create(data, expir_sec)
        self._response.set_cookie(sn_name, sn_num)

        self._session = {}
        self._session['user_info'] = user_info
        self._render.view['_session'] = self._session
        self._render.view['path'] = path

    @auth.session(auth.SESSION_LEVEL['user'])
    def action_logout(self):
        '登出页面'
        mod_ss = ModelSession()
        mod_ss.clear(self._session['sn'])

        self._response.clear_cookie('sn')
        self._render.view['_session'] = {}

    @auth.session(auth.SESSION_LEVEL['visitor'])
    def action_reg(self):
        '注册表单页面'
        pass

    @auth.method('post')
    @auth.session(auth.SESSION_LEVEL['visitor'])
    def action_regproc(self):
        '注册处理页面'
        import uuid

        expir_sec = CONF['expir_sec']
        sn_name = CONF['sn_name']

        # 表单信息检查
        form = self._request.form
        check_list = [
                'username',
                'passwd',
                'realname',
                'birthday',
                'mobile',
                'postcode',
                'address',
                ]
        user_info, error_type = ValidatorPassport.check_from_dict(
                form, check_list)
        if error_type:
            return self.error_type(error_type)

        # 从数据库检查并创建用户信息
        user_info['passwd'] = FilterPassport.passwd_hash(
                user_info['username'], user_info['passwd'])
        mod_usr = ModelUser()
        user_info = mod_usr.create(user_info)
        if not user_info:
            return self.error_type('create_failed')
        self._render.view['user_info'] = user_info

        # 创建session
        data = {}
        data['user_id'] = user_info['id']
        data['token'] = uuid.uuid4().hex
        mod_ss = ModelSession()
        sn_num = mod_ss.create(data, expir_sec)
        self._response.set_cookie(sn_name, sn_num)

    @auth.method('post')
    @auth.session(auth.SESSION_LEVEL['visitor'])
    def action_checkuser(self):
        '判断用户是否存在，用json格式返回'

        self._render.mode = 'json'

        form = self._request.form
        check_list = ['username', ]
        user_info, error_type = ValidatorPassport.check_from_dict(
                form, check_list)
        if error_type:
            self._render.view = {'result': 'invalidate'}
            return

        # 从数据库检查用户登录信息
        mod_usr = ModelUser()
        res = mod_usr.is_username_exist(user_info['username'])
        if res:
            self._render.view = {'result': 'existed'}
        else:
            self._render.view = {'result': 'ok'}


application = HandlePassport()
